package com.example.wifi4server;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class WriteTask implements Runnable {

    public boolean bStop = false;
    public String m_msg;

    public Socket mSocket;
    private Handler mHandler;
    private OutputStream outputStream;

    public WriteTask(Socket socket,String msg,Handler handler){
        mSocket = socket;
        m_msg = msg;
        mHandler = handler;

        try {
            outputStream = (mSocket != null) ? mSocket.getOutputStream() : null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        Log.i("ConnectThread", "发送数据:" + (outputStream == null));
        if (bStop == true)
            return;
        if(mSocket == null)
            return;
        if (mSocket.isConnected() == false)
            return;
        if (mSocket.isClosed() == true)
            return;
        if (outputStream == null)
            return;

        if (outputStream != null &&
                m_msg.equals("") == false) {
            try {
                outputStream.write(m_msg.getBytes());
                Log.i("ConnectThread", "发送消息：" + m_msg);
                Message message = Message.obtain();
                message.what = MainActivity.SEND_MSG_SUCCSEE;
                Bundle bundle = new Bundle();
                bundle.putString("MSG", new String(m_msg));
                message.setData(bundle);
                mHandler.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                Message message = Message.obtain();
                message.what = MainActivity.SEND_MSG_ERROR;
                Bundle bundle = new Bundle();
                bundle.putString("MSG", new String(m_msg));
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
            m_msg = "";
        }
    }
}
